const crypto = require('crypto');
const qr = require('qr-image')
module.exports = {
  // 成功提示
  apiSuccess(data = '', msg = 'ok', code = 200) {
    this.body = { msg, data };
    this.status = code;
  },
  // 失败提示
  apiFail(data = '', msg = 'fail', code = 400) {
    this.body = { msg, data };
    this.status = code;
  },
  mkdirsSync(dirname) {
		if (fs.existsSync(dirname)) {
			return true;
		} else {
			if (this.mkdirsSync(path.dirname(dirname))) {
				fs.mkdirSync(dirname);
				return true;
			}
		}
	},
	// 验证密码
	async checkPassword(password, hash_password) {
	    // 先对需要验证的密码进行加密
			const hmac = crypto.createHash("sha256", this.app.config.crypto.secret);
			hmac.update(password);
			password = hmac.digest("hex");
	    if(password !== hash_password){
			this.throw(400, '密码错误');
		}
		return true;
	},
	// 生成token
	getToken(value) {
	    return this.app.jwt.sign(value, this.app.config.jwt.secret);
	},
	// 验证方法
	async checkToken(token,ws = false){
		let user = this.app.jwt.verify(token, this.app.config.jwt.secret)
		if(ws){
		   if(!user || (token != await this.service.cache.get('user_'+user.id))) {
			return false
		  } 
		}
		
		return user
	},
	// 发送或者存到消息队列中
	async sendAndSaveMessage(to_id, message, msg="ok"){
		const { app, service } = this
		// 这里this就是ctx
		let current_user_id = this.authUser.id
		
		// 拿到接收用户所在子进程
	    let pid = await service.cache.get('online_' + to_id);
		if (pid) {
			// 消息推送
			app.messenger.sendTo(pid, 'send', {
				to_id, message, msg
			});
			// 存到历史记录当中
			if (msg === 'ok') {
				service.cache.setList(`chatlog_${to_id}_${message.chat_type}_${current_user_id}`, message);
			}
		} else {
			service.cache.setList('getmessage_' + to_id, {
				message,
				msg
			});
		}
	/*	// 拿到对方socket
		 let socket = null
		if(app.ws.user && app.ws.user[to_id]){
			socket = app.ws.user[to_id]
		}
		// 对方是否在线
		if(!socket){
			// 加入redis缓存中
			service.cache.setList('getmessage_'+to_id, { message, msg })
		}else{
			socket.send(JSON.stringify({
					msg,
					data: message
			}))
			// 存到历史记录中
			if(msg == 'ok') service.cache.setList(`chatlog_${to_id}_${message.chat_type}_${current_user_id}`, message)
		}*/ 
	},
	
	// 发送消息
 	async send(to_id, message, msg = 'ok') {
		const { app, service } = this;
		let current_user_id = this.authUser.id;

		// 拿到接受用户所在子进程
		let pid = await service.cache.get('online_' + to_id);

		if (pid) {
			// 消息推送
			app.messenger.sendTo(pid, 'send', {
					to_id, message, msg
			});
		}
	},   
	//生成二维码
	qrcode(data){
		let image = qr.image(data, { size: 10 });
		// this就是ctx
		this.response.type = 'image/png';
		this.body = image;
	},
	async getOnline(id){
	    const { service, app } = this;
	    return await service.cache.get('online_' + id)
	},
	// 生成唯一id
	genID(length) {
	  return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36);
	},
	// 用户上线
	async online(user_id) {
        const { service, app } = this;
        
        let pid = process.pid;
        let opid = await service.cache.get("online_" + user_id);
        // 用户有登录记录,不在同一个进程,当前进程已在前面处理过
        if (opid && (pid != opid)) {
            // 这里是异步操作,会把if后面代码先执行
            app.messenger.sendTo(opid, "offline", user_id);
        }
        
        setTimeout(async () => {
            
                app.ws.user[user_id] = this.websocket;
                await service.cache.set("online_" + user_id, pid);
                console.log('ctx_online在线人数==================',Object.keys(app.ws.user).length)
                this.websocket.send(JSON.stringify({
                msg:'connOk'
            }));
        }, 300);
        
    }

};